/**
 *
 */
package com.supersit.greensproject.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;

import com.supersit.greensproject.R;


/**
 * @author Administrator
 */
public class DBut {
    private static SQLiteDatabase database;
    public static final String DATABASE_FILENAME = "greens.db"; // 这个是DB文件名字
    public static final String PACKAGE_NAME = "com.supersit.greensproject"; // 这个是自己项目包路径
    public static final String DATABASE_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"
            + PACKAGE_NAME + "/databases"; // 获取存储位置地址
    public static String databaseFilename = DATABASE_PATH + "/"
            + DATABASE_FILENAME;

    @Nullable
    public static SQLiteDatabase openDatabase(Context context) {
        try {
            File dir = new File(DATABASE_PATH);
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!(new File(databaseFilename)).exists()) {
                InputStream is = context.getResources().openRawResource(
                        R.raw.greens);
                FileOutputStream fos = new FileOutputStream(databaseFilename);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }

                fos.close();
                is.close();
            }
            database = SQLiteDatabase.openOrCreateDatabase(databaseFilename,
                    null);
            return database;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("tag", e.getMessage());
        }
        return null;
    }

    public static void deleteTableData() {
        database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
        database.execSQL("delete from base");
        //database.execSQL("update sqlite_sequence SET seq = 0 where name ='market'");// 自增长ID为0
        database.close();
    }
}
